package com.atguigu.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class PassportApiController {

    //  api/user/passport/login
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request){
        UserInfo info = userInfoService.login(userInfo);
        if(info!=null){
            HashMap<String, Object> map = new HashMap<>();
            String token = UUID.randomUUID().toString();
            map.put("token",token);
            map.put("nickName",info.getNickName());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId",info.getId().toString());
            jsonObject.put("ip", IpUtil.getIpAddress(request));
            String loginKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
            redisTemplate.opsForValue().set(loginKey,jsonObject.toJSONString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(map);
        }
        return Result.fail().message("登陆失败");
    }

    @GetMapping("/logout")
    public Result logout(@RequestHeader String token){
        String loginKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.delete(loginKey);
        return Result.ok();
    }
}
